<?php defined('IN_LK') or die('Access Denied');
define('IN_ADMIN', 1);
lk::lo('session_' . SESSION_STORAGE);
class admin_common
{
	public $userid;
	public $username;
	
	/**
	 * 公共动作及过滤
	 */
	public function __construct()
	{
		self::check_ip();
		self::check_login();
		self::check_priv();
		self::admin_log();
		self::check_timeout();
		$_POST   = isset($_POST)   ? new_htmlspecialchars($_POST)   : '';
		$_GET    = isset($_GET)    ? new_htmlspecialchars($_GET)    : '';
		$_COOKIE = isset($_COOKIE) ? new_htmlspecialchars($_COOKIE) : '';
	}

	/**
	 * 检查用户是否长时间未操作（定义超时）
	 */
	final public static function check_timeout()
	{
		if(M == 'admin' && C == 'index' && A == 'login')
		{
			return true;
		}
		if(!isset($_SESSION['check_time']) || !$_SESSION['check_time'])
		{
			$_SESSION['check_time'] = TIME;
		}
		if(TIME - $_SESSION['check_time']>= ADMINTIMEOUT)
		{
			self::login_set();
			showmsg(LANG('check_timeout'), true, '?m=admin&c=index&a=login', true, '', true);
		}
		$_SESSION['check_time'] = TIME;
	}
	
	/**
	 * 记录日志
	 */
	final public static function admin_log()
	{
		$log = defined('ADMINLOG') && ADMINLOG ? ADMINLOG : 0;
		if($log)
		{
			$action = A;
			$no_log = EXCLUD_ACTION;
			$no_log = explode(',', $no_log);
			if(strpos($action, 'ajax') !== false || in_array($action, $no_log))
			{
				return true;
			}
			$log_db = lk::load_model('log');
			$info['ip'] = get_ip();
			$info['time'] = date('Y-m-d H:i:s', TIME);
			$info['username'] = get_cookie('username');
			$info['userid']   = isset($_SESSION['userid']) ? $_SESSION['userid'] : 0;
			$info['query'] = relative_url();//'m=' . M . '&c=' . C . '&a=' . A;
			$log_db->insert($info);
		}
		return true;
	}
	
	/**
	 * ip禁止
	 */
	final public static function check_ip()
	{
		$ipbanned = lk::load_model('ipbanned');
		if($ipbanned->is_banned())
		{
			showmsg(LANG('your_ip_no_access'), false);
		}
	}

	/**
	 * 权限判断
	 * @return boolean
	 */
	final public static function check_priv()
	{
		if(C == 'index' && M == 'admin')
		{
			return true;
		}
		if($_SESSION['roleid'] == 1)
		{
			return true;
		}
		$a = A == 'initialize' ? '' : A;
		$db = lk::load_model('admin_role_priv');
		$res = $db->get_one('roleid', "`roleid`='" . $_SESSION['roleid'] . "' AND `m`='" . M . "' AND `c`='" . C . "' AND `a`='" . $a . "'");
		if(!$res)
		{
			showmsg(LANG('you_have_no_access'));
		}
		return true;
	}
	
	/**
	 * 检测是否登录
	 * @return mixed
	 */
	final public static function check_login()
	{
		if(!isset($_SESSION['userid']) || !isset($_SESSION['roleid']) || !$_SESSION['userid'] || !$_SESSION['roleid'])
		{
			if(M == 'admin' && C == 'index' && A == 'login')
			{
				return true;
			}
			else
			{
				//header('Location:index.php?m=admin&a=login');
				showmsg(LANG('please_login'), false, 'index.php?m=admin&a=login', true, '', true);
			}
		}
		if(isset($_SESSION['userid']) && isset($_SESSION['roleid']) && $_SESSION['userid'] && $_SESSION['roleid'] && M == 'admin' && C == 'index' && A == 'login')
		{
			showmsg(LANG('you_are_logined'), true, 'index.php?m=admin');
		}
	}
	
	/**
	 * 登录session及cookie设置
	 * @param array $user 用户数据数组 必须包含roleid及userid username 不传参则销毁
	 * @return boolean
	 */
	final public static function login_set($user = array())
	{
		if(!$user)
		{		
			$_SESSION['userid'] = 0;
			$_SESSION['roleid'] = 0;
			$_SESSION['lock_screen'] = 0;
			$_SESSION['check_time'] = 0;
			set_cookie('userid', '');
			set_cookie('username', '');
			return true;
		}
		$_SESSION['userid'] = $user['userid'];
		$_SESSION['roleid'] = $user['roleid'];
		$_SESSION['lock_screen'] = 0;
		set_cookie('userid', $user['userid']);	//后台实时登录
		set_cookie('username', $user['username']);
		return true;
	}
	
	/**
	 * 加载模板
	 * @param string $file 模板文件名,如index.tpl.php的index
	 * @param string $module 模型名 
	 * @param mixed
	 */
	final public static function admin_t($file = 'index', $module = '')
	{
		$module = $module ? $module : M;
		$filename = TPL_ROOT . $module . DIRECTORY_SEPARATOR . $file . '.tpl.php';
		return is_file($filename) ? $filename : false; 
	}

	/**
	 * 仅生成二级菜单
	 * @return array('title' => '数组', 'guides' => '数组')
	 */
	final public static function supmenu()
	{
		$return = $title = $guides = array();
		$menu_db = lk::load_model('menu');
		$priv_db = lk::load_model('admin_role_priv');
		$tree    = lk::lo('tree');
		$res = $menu_db->get('id,parentid,name,title,m,c,a', '`display`=\'1\'', '`listorder`,`id` ASC', '', '', 'id');
		/**
		 * 权限
		 */
		if(isset($_SESSION['roleid']) && $_SESSION['roleid'] != 1)
		{
			foreach($res as $r_key => $r_value)
			{
				$r = $priv_db->get_one('roleid', '`m`=\'' . $r_value['m'] . '\' AND `c`=\'' . $r_value['c'] . '\' AND `a`=\'' . $r_value['a'] . '\' AND `roleid`=\'' . $_SESSION['roleid'] . '\'');
				if(!$r)
				{
					unset($res[$r_key]);
				}
			}
		}
		$tree->input_arr = $res;
		$data = $tree->get_tree_data(0);
		/**
		 * 只生成二级菜单，这么拼装因为json要用到
		 */
		foreach($data as $key => $value)
		{
			if($value['parentid'] == 0)
			{
				$title[$value['name']] = $value['title'];
			}
			if($value['child'])
			{
				foreach($value['child'] as $child)
				{
					$guides[$value['name']][$value['name']][$child['name']]= 
					array($child['title'], 
					      '?m=' . $child['m'] . '&c=' . $child['c'] . '&a=' . $child['a'], 
						  $child['id']);
				}
			}
		}
		$menus = array('guides' => $guides, 'title' => $title);
		set_cache('menu_role' . $_SESSION['roleid'], $menus);
		return $menus;
	}
}